<template>
  <div class="echart">
    <el-card
      :body-style="{
        padding: '20px',
        minHeight: 'calc(100vh - 100px)',
      }"
    >
      <div class="statisticsPane" v-loading="statistics_loading">
        <div class="statisticsDiv" v-if="statisticsData">
          <div class="btnRight">
            <el-button
              type="primary"
              size="mini"
              @click="saveEchartImage"
              :loading="btn_loading"
              >保存图片</el-button
            >
          </div>
          <div
            class="echartParentDiv"
            :style="
              'overflow-x:' +
              (Number(echartParentWidth) <
              Number(echartContentWidth - 80)
                ? 'auto'
                : 'hidden')
            "
            ref="echartParentDiv"
          >
            <div
              class="echartList"
              ref="echartContent"
              :style="'width:' + echartContentWidth + 'px'"
            >
              <div class="cityDiv" ref="cityEchart">
                <div class="amoutTips"><span></span>总预算</div>
                <div class="cityChart" id="cityChart"></div>
                <div class="cityMsg">
                  <div class="cityName">
                    <span>{{ statisticsData.level_name }}</span>
                    <el-tag
                      size="mini"
                      :type="
                        getLevelTypeTag(statisticsData.level_type)
                      "
                      >{{ statisticsData.level_type }}</el-tag
                    >
                  </div>
                  <div class="amount">
                    <span class="take_amount"
                      >￥{{ statisticsData.p_take_amount }}</span
                    >
                    /
                    <span>￥{{ statisticsData.p_max_amount }}</span>
                  </div>
                </div>
                <div
                  class="chartLineBottom"
                  v-if="
                    statisticsData.child_list &&
                    statisticsData.child_list.length > 0
                  "
                ></div>
              </div>
              <div
                class="districtCon"
                :style="
                  'border-top:' +
                  (statisticsData.child_list &&
                  statisticsData.child_list.length == 0
                    ? 'none'
                    : '1px solid #ddd')
                "
              >
                <div
                  class="districtDiv"
                  v-for="(item, index) in statisticsData.child_list"
                  :key="index"
                >
                  <div class="chartLineTop">
                    <div class="borderLine"></div>
                  </div>
                  <div class="districtList">
                    <div class="districtChart"></div>
                    <div class="districtMsg">
                      <div class="districtName">
                        <span>{{ item.level_name }}</span>
                        <el-tag
                          size="mini"
                          :type="getLevelTypeTag(item.level_type)"
                          >{{ item.level_type }}</el-tag
                        >
                      </div>
                      <div class="amount">
                        <span class="take_amount"
                          >￥{{ item.p_take_amount }}</span
                        >
                        /
                        <span>￥{{ item.p_max_amount }}</span>
                      </div>
                    </div>
                  </div>
                  <!-- districtList-区县信息-end -->

                  <div class="branchList">
                    <div
                      class="branchItem"
                      v-for="(item1, index) in item.child_list"
                      v-if="item.child_list"
                      :key="index"
                    >
                      <div class="chartLineTop">
                        <div class="borderLine"></div>
                      </div>
                      <div class="branchChart"></div>
                      <div class="branchMsg">
                        <div class="branchName">
                          <span>{{ item1.level_name }}</span>
                          <el-tag
                            size="mini"
                            :type="getLevelTypeTag(item1.level_type)"
                            >{{ item1.level_type }}</el-tag
                          >
                        </div>
                        <div class="amount">
                          <span class="take_amount"
                            >￥{{ item1.p_take_amount }}</span
                          >
                          /
                          <span>￥{{ item1.p_max_amount }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                  <!-- branchList-网点信息-end -->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import "echarts/theme/macarons.js";
//将整个页面转换成canvas
import html2canvas from "html2canvas";

export default {
  name: "statisticsPane",
  components: {},
  data() {
    return {
      statisticsData: {
        //市公司
        cityData: {},
        //list：区县及网点的数据，child:[]:网点数据
        child_list: [],
      },
      statistics_loading: false,
      btn_loading: false, //加载中按钮
      echartContentWidth: "",
      echartParentWidth: "",
    };
  },
  methods: {
    //机构类型
    getLevelTypeTag(type) {
      switch (type) {
        case "网点":
          return "blue";
          break;
        case "区县":
          return "success";
          break;
        case "市公司":
          return "danger";
          break;
      }
    },

    //保存图片
    saveEchartImage() {
      console.log(
        "this.$refs.echartContent",
        this.$refs.echartContent.offsetWidth
      );
      this.btn_loading = true;
      this.$refs.echartParentDiv.style.transform = "scaleY(1)";
      this.$refs.echartContent.style.transform = "scaleY(1)";

      // 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等
      html2canvas(this.$refs.echartContent, {
        // width: 30, //截图宽度
        // height: 50, //截图高度
        backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色（null）
        useCORS: true, //支持图片跨域
        scale: 1, //设置放大的倍数
      }).then((canvas) => {
        // 把生成的base64位图片上传到服务器,生成在线图片地址
        let url = canvas.toDataURL("image/png"); // toDataURL: 图片格式转成 base64
        this.saveFile(url, `2023年微信礼包活动派发统计`);
      });
    },

    //图片保存到本地
    saveFile(data, filename) {
      this.btn_loading = false;
      //document.createElementNS():创建一个具有指定的命名空间 URI 和限定名称的元素
      //参考：https://developer.mozilla.org/zh-CN/docs/Web/API/Document/createElementNS
      const save_link = document.createElementNS(
        "http://www.w3.org/1999/xhtml",
        "a"
      );
      save_link.href = data;
      save_link.download = filename;

      //参考：https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent
      const event = new MouseEvent("click", {
        bubbles: true,
        cancelable: true,
        view: window,
      });
      save_link.dispatchEvent(event);

      this.$refs.echartParentDiv.style.transform = "scaleY(-1)";
      this.$refs.echartContent.style.transform = "scaleY(-1)";
    },

    //echart设置
    setEchartsOption(myChartName, take_amount, echartData, isLegend) {
      let that = this;
      console.log("myChartName-echartData", myChartName, echartData);
      myChartName.setOption({
        color: ["#119A30", "#d2d2d2"],
        title: {
          text: isLegend ? `2023年微信礼包活动派发统计` : "",
          left: "center",
          top: 0,
          textStyle: {
            color: "#303133",
            fontSize: 14,
          },
        },
        tooltip: {
          trigger: "item",
          formatter: "{b} : {c} ({d}%)",
          position: function (point, params, dom, rect, size) {
            dom.style.transform = "translateZ(0)";
          },
        },
        legend: isLegend ? { right: "top", width: 200 } : "",
        series: [
          {
            type: "pie",
            radius: ["50%", "70%"],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: true,
                position: "center",
                formatter: function () {
                  return take_amount;
                },
                textStyle: {
                  fontSize: 20,
                  color: "#119A30",
                },
              },
            },
            data: echartData, // 渲染每个图表对应的数据
          },
        ],
      });
    },

    //加载列表
    async init() {
      let response;
      //this.statistics_loading = true;
      //根据接口返回的数据
      // await this.$axios
      //   .get(`/admin/xx/`, {
      //     params: {
      //       cash_activity_id: this.$route.query.id,
      //     },
      //   })
      //   .then((res) => {
      //     this.$message.success("数据加载成功!");
      //     this.date_now = res.date_now;
      //     this.statisticsData = res.statisticsData;
      //     response = res;
      //   })
      //   .catch((err) => {
      //     this.statisticsData = "";
      //     if (err.response) {
      //       this.$message.error(
      //         err.response.data.error || err.response.data.detail
      //       );
      //     }
      //   })
      //   .finally(() => {
      //     this.statistics_loading = false;
      //   });
      response = {
        statisticsData: {
          level_name: "市公司",
          level_type: "市公司",
          p_max_amount: "17542.00",
          p_remain_amount: "1710.00",
          p_take_amount: "15832.00",
          amountData: [
            { name: "已派发", value: 15832 },
            { name: "剩余额度", value: 1710 },
            { name: "总额度", value: 17542 },
          ],
          child_list: [
            {
              level_name: "区县营业所",
              level_type: "区县",
              p_max_amount: "2742.00",
              p_remain_amount: "0.00",
              p_take_amount: "2742.00",
              amountData: [
                { name: "已派发", value: 158 },
                { name: "剩余额度", value: 42 },
                { name: "总额度", value: 200 },
              ],
              child_list: [
                {
                  level_name: "网点营业所",
                  level_type: "网点",
                  p_max_amount: "2742.00",
                  p_remain_amount: "0.00",
                  p_take_amount: "742.00",
                  amountData: [
                    { name: "已派发", value: 158 },
                    { name: "剩余额度", value: 42 },
                    { name: "总额度", value: 200 },
                  ],
                },
              ],
            },
            {
              level_name: "区县营业所",
              level_type: "区县",
              p_max_amount: "2742.00",
              p_remain_amount: "0.00",
              p_take_amount: "270.00",
              amountData: [
                { name: "已派发", value: 158 },
                { name: "剩余额度", value: 42 },
                { name: "总额度", value: 200 },
              ],
              child_list: [],
            },
          ],
        },
      };
      this.statisticsData = response.statisticsData;
      return response;
    },

    async echartShow() {
      this.init().then((res) => {
        console.log("res", res);
        this.statisticsData = res.statisticsData;
        let arr = [];
        this.echartParentWidth =
          this.$refs.echartParentDiv.offsetWidth; //echart图表的宽度

        this.echartContentWidth =
          Number(this.$refs.cityEchart.offsetWidth) <=
          Number(this.statisticsData.child_list.length) * 250
            ? this.statisticsData.child_list.length * 250 + 80
            : Number(this.$refs.cityEchart.offsetWidth) + 80;

        console.log(
          "this.echartContentWidth",
          this.echartContentWidth
        );

        this.statisticsData.child_list.forEach((item) => {
          if (item.child_list) {
            arr.push(item.child_list.length);
          } else {
            arr.push(0);
          }
        });
        console.log("arr", arr); //[1,0]：区县的子类个数

        let arrNew = [0];
        arr.forEach((item, index) => {
          arrNew.push(item + arrNew[index]);
        });

        console.log("arrNew", arrNew); //[0,1,1]

        var echarts = require("echarts");
        var cityCharts = document.getElementById("cityChart");
        var districtCharts =
          document.getElementsByClassName("districtChart"); // 对应地使用ByClassName
        var branchCharts =
          document.getElementsByClassName("branchChart"); // 对应地使用ByClassName

        //市公司-echart数据-start
        var cityChart = echarts.init(cityCharts);
        let city_take_amount =
          this.statisticsData.p_max_amount == 0
            ? "0.00" + "%"
            : (
                (this.statisticsData.p_take_amount /
                  this.statisticsData.p_max_amount) *
                100
              ).toFixed(2) + "%";
        let city_amountData = this.statisticsData.amountData.slice(
          0,
          2
        );
        this.setEchartsOption(
          cityChart,
          city_take_amount,
          city_amountData,
          1
        );
        window.onresize = cityChart.resize; //图表自适应浏览器大小
        //市公司-echart数据-end

        for (
          var i = 0;
          i < this.statisticsData.child_list.length;
          i++
        ) {
          //区县-echart数据-start
          var districtChart = echarts.init(districtCharts[i]);
          let district_take_amount =
            this.statisticsData.child_list[i].p_max_amount == 0
              ? "0.00%"
              : (
                  (this.statisticsData.child_list[i].p_take_amount /
                    this.statisticsData.child_list[i].p_max_amount) *
                  100
                ).toFixed(2) + "%";
          let district_amountData = this.statisticsData.child_list[
            i
          ].amountData.slice(0, 2);
          this.setEchartsOption(
            districtChart,
            district_take_amount,
            district_amountData
          );
          //区县-echart数据-end

          //网点-echart数据-start
          if (
            this.statisticsData.child_list[i].child_list &&
            this.statisticsData.child_list[i].child_list.length > 0
          ) {
            for (
              var k = 0;
              k < this.statisticsData.child_list[i].child_list.length;
              k++
            ) {
              let branch_take_amount =
                this.statisticsData.child_list[i].child_list[k]
                  .p_max_amount == 0
                  ? "0.00%"
                  : (
                      (this.statisticsData.child_list[i].child_list[k]
                        .p_take_amount /
                        this.statisticsData.child_list[i].child_list[
                          k
                        ].p_max_amount) *
                      100
                    ).toFixed(2) + "%";
              let branch_amountData = this.statisticsData.child_list[
                i
              ].child_list[k].amountData.slice(0, 2);

              let branchChart = echarts.init(
                branchCharts[k + arrNew[i]]
              );
              console.log(
                "branch_amountData",
                i,
                k,
                branch_amountData
              );

              this.setEchartsOption(
                branchChart,
                branch_take_amount,
                branch_amountData
              );
            }
          }
          //网点-echart数据-end
        }
      });
    },
  },
  mounted() {
    this.echartShow();
  },
};
</script>
<style lang="scss" scoped>
.echartParentDiv {
  width: calc(100vw - 100px);
  overflow-x: auto;
  transform: scaleY(-1);
}
.echartList {
  background: #fff;
  padding: 20px 40px 20px 40px;
  font-size: 14px;
  position: relative;
  transform: scaleY(-1);
  .amount {
    font-weight: bold;
    .take_amount {
      color: #119a30;
    }
  }

  .cityDiv {
    position: relative;
    padding-bottom: 52px;
    // position: absolute;
    // top: 20px;
    // left: 9%;
    .cityName {
      display: flex;
      height: 25px;
      justify-content: center;
      align-items: center;
      margin-bottom: 2px;
      span:nth-child(1) {
        display: inline-block;
        margin-right: 5px;
      }
    }
    .chartLineBottom {
      width: 1px;
      height: 35px;
      background: #ddd;
      position: absolute;
      bottom: 0;
      left: 50%;
      margin-left: -0.5px;
    }
  }

  .districtCon {
    display: flex;
    background-size: 100% 100%;
    border-top: 1px solid #ddd;
    .districtDiv {
      width: 250px;
      position: relative;
      padding-top: 42px;
      .chartLineTop {
        position: absolute;
        top: 0;
        left: 50%;
        margin-left: -4.5px;
        width: 9px;
        padding-bottom: 7px;
        background: url("~@/assets/images/echartTopIco.png") bottom
          center no-repeat;
        .borderLine {
          width: 1px;
          height: 35px;
          background: #ddd;
          margin: 0 auto;
        }
      }
      .districtMsg {
        width: 250px;
        text-align: center;
        margin-bottom: 25px;
      }
      .districtChart {
        width: 250px;
        height: 160px;
      }
      .branchChart {
        width: 250px;
        height: 160px;
      }
      .districtList {
        width: 220px;
        height: 240px;
      }
    }
  }
  .branchItem {
    width: 250px;
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    position: relative;
    padding-top: 42px;
    .branchMsg {
      width: 250px;
      text-align: center;
      margin-bottom: 25px;
    }
  }
  .cityDiv {
    text-align: center;
    width: calc(100vw - 100px);
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    position: relative;
    .amoutTips {
      position: absolute;
      top: 0;
      right: 0;
      z-index: 100;
      width: 100px;
      font-size: 12px;
      display: flex;
      align-items: center;
      height: 22px;
      margin-right: -5px;
      color: #555;
      span {
        display: inline-block;
        width: 10px;
        border-bottom: 3px solid #000;
        margin-right: 2px;
      }
    }
  }
  .cityChart {
    width: calc(100vw - 100px);
    height: 160px;
    margin: 0 100px;
  }
}
.statisticsPane {
  position: relative;
  padding-top: 50px;
}
.statisticsPane .btnRight {
  position: absolute;
  top: 0px;
  right: 0px;
  z-index: 100;
}

.echartParentDiv::-webkit-scrollbar {
  width: 3px;
  height: 9px;
}
.echartParentDiv::-webkit-scrollbar-track {
  background-color: #fff;
  border-radius: 10px;
}
.echartParentDiv::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 20px;
}
</style>
